package cn.com.infcn.monitor.task.impl;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;

import org.apache.mina.core.session.IoSession;
import org.hyperic.sigar.SigarException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.infcn.monitor.bean.IFCDirectory;
import cn.com.infcn.monitor.bean.IFCRequestBean;
import cn.com.infcn.monitor.bean.IFCResponseBean;
import cn.com.infcn.monitor.util.IFCMinitorConstanst;
import cn.com.infcn.monitor.util.IFCMonitorUtil;

/**
 * 获取指定目录的元数据信息
 * 
 * @author jjs
 *
 */
public class DirectoryTask extends BaseTask {

	private static Logger logger = LoggerFactory.getLogger(DirectoryTask.class);

	public DirectoryTask(IoSession session, Object message) {
		super(session, message);
	}

	@Override
	public void execute() throws Exception {
		IFCResponseBean result = directory();
		sendResponse(result);
	}

	private IFCResponseBean directory() throws SigarException {
		IFCResponseBean result = new IFCResponseBean();

		try {
			IFCRequestBean request = (IFCRequestBean) message;
			// 获取查询参数
			Object obj = request.getParams();
			// 判断参数类型是否正确
			if (obj instanceof String) {
				String dirPath = (String) obj;
//				dirPath = "d:\\test.txt";
				IFCDirectory dir = new IFCDirectory();
				dir.setDirPath(dirPath);
				File f = new File(dirPath);
				// 判断文件路径是否正确
				if (f.exists()) {
					dir.setIsExists(1); // 是否存在
					dir.setIsHidden(IFCMonitorUtil.convertInt(f.isHidden())); // 是否隐藏文件
					Path filePath = Paths.get(dirPath); // 文件路径
					BasicFileAttributes ra = Files.readAttributes(filePath, BasicFileAttributes.class);
					dir.setCreateDate(ra.creationTime().toMillis()); // 文件创建时间
					dir.setLastAccessTime(ra.lastAccessTime().toMillis()); // 最后访问时间
					dir.setSize(ra.size()); // 文件大小
					dir.setLastModifiedTime(ra.lastModifiedTime().toMillis()); // 最后修改时间
					dir.setIsSymbolicLink(IFCMonitorUtil.convertInt(ra.isSymbolicLink())); //
					dir.setIsDirectory(IFCMonitorUtil.convertInt(ra.isDirectory())); //
					dir.setIsRegularFile(IFCMonitorUtil.convertInt(ra.isRegularFile())); //
				} else {
					dir.setIsExists(0);
				}
				result.setResult(dir);
				result.setResponseCode(IFCMinitorConstanst.MONITOR_RESPONSE_CODE_OK);
			} else {
				result.setResponseCode(IFCMinitorConstanst.MONITOR_RESPONSE_CODE_ERROR);
				result.setResponseMsg("参数异常!");
				result.setResult(null);
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			result.setResponseCode(IFCMinitorConstanst.MONITOR_RESPONSE_CODE_ERROR);
			result.setResponseMsg(e.getMessage());
		}

		return result;
	}

}
